package com.sc.web.gwt.server.service;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sc.web.gwt.client.service.GetUserService;
import com.sc.web.gwt.server.persistence.AdminPersistence;
import com.sc.web.gwt.server.persistence.AgentAdminPersistence;
import com.sc.web.gwt.shared.model.Admin;
import com.sc.web.gwt.shared.model.AgentAdmin;

import java.util.List;

public class GetUserServiceImpl extends RemoteServiceServlet implements GetUserService {
    private final AdminPersistence adminPersistence = new AdminPersistence();
    private final AgentAdminPersistence agentAdminPersistence = new AgentAdminPersistence();

    public Admin isAdminValid(String userName, String password) {
        List<Admin> adminList = adminPersistence.getAllAdmins();
        for (Admin admin : adminList) {
            if (admin.getAdminAccount().equals(userName) && admin.getAdminPassword().equals(password)) {
                getThreadLocalRequest().getSession().setAttribute("userId", admin.getAdminId());
                getThreadLocalRequest().getSession().setAttribute("userType", "admin");
                return admin;
            }
        }
        return null;
    }

    public AgentAdmin isAgentAdminValid(String userName, String password) {
        List<AgentAdmin> agentAdminList = agentAdminPersistence.getAllAgentAdmins();
        for (AgentAdmin agentAdmin : agentAdminList) {
            if (agentAdmin.getState().equals("Valid") && agentAdmin.getAgentAdminAccount().equals(userName) && agentAdmin.getAgentAdminPassword().equals(password)) {
                getThreadLocalRequest().getSession().setAttribute("userId", agentAdmin.getAgentAdminId());
                getThreadLocalRequest().getSession().setAttribute("userType", "agent");
                return agentAdmin;
            }
        }
        return null;
    }

    public String isUserLoggedIn() {
        return (String)getThreadLocalRequest().getSession().getAttribute("userType");
    }

    public void logOut() {
        getThreadLocalRequest().getSession().setAttribute("userId", null);
        getThreadLocalRequest().getSession().setAttribute("userType", null);
    }

    public Admin getAdminInfo(int adminId) {
        Admin admin = adminPersistence.getAdmin(adminId);
        return admin;
    }

    public AgentAdmin getAgentAdminInfo(int agentAdminId) {
        AgentAdmin agentAdmin = agentAdminPersistence.getAgentAdmin(agentAdminId);
        return agentAdmin;
    }
}
